<template>
	<view class="container" ref="sign">
		<view class="sigh-btns">
			<button class="btn" @tap="handleCancel">关闭</button>
			<button class="btn" @tap="handleReset">重写</button>
			<button class="btn" @tap="handleConfirm">确认</button>
		</view>
		<view class="sign-box">
			<canvas class="mycanvas" :style="{width:width +'px',height:height +'px'}" canvas-id="mycanvas"
				@touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>

			<canvas canvas-id="camCacnvs" :style="{width:height +'px',height:width +'px'}" class="canvsborder"></canvas>
		</view>
	</view>

</template>
<script>
	import config from '@/config';
	import {
		getMediaPath
	} from '@/api/note.js'
	var x = 20;
	var y = 20;
	var tempPoint = []; //用来存放当前画纸上的轨迹点
	var id = 0;
	var type = '';
	let that;
	let canvasw;
	let canvash;
	export default {
		data() {
			return {
				ctx: '', //绘图图像
				points: [], //路径点集合,
				width: 0,
				height: 0,
				modeId: "",
				orderId: "",
				userId: "",
				nameS: "",
				cardId: "",
				fileUrl: ""
			};
		},

		onLoad(option) {
			that = this;
			that.modeId = option.modeId;
			that.orderId = option.orderId;
			that.nameS = option.name;
			that.cardId = option.IDcard;
			id = option.id;
			type = option.type;
			this.ctx = uni.createCanvasContext('mycanvas', this); //创建绘图对象
			//设置画笔样式
			this.ctx.lineWidth = 4;
			this.ctx.lineCap = 'round';
			this.ctx.lineJoin = 'round';

			uni.getSystemInfo({
				success: function(res) {
					that.width = res.windowWidth * 0.8;
					that.height = res.windowHeight * 0.85;
				}
			});
		},
		methods: {
			getParams(data) {
				console.log(data)
			},
			//触摸开始，获取到起点
			touchstart: function(e) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};

				/* **************************************************
                              #由于uni对canvas的实现有所不同，这里需要把起点存起来
                           * **************************************************/
				this.points.push(startPoint);

				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},

			//触摸移动，获取到路径点
			touchmove: function(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
				tempPoint.push(movePoint);
			},

			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend: function() {
				this.points = [];
			},

			/* ***********************************************
                    #   绘制笔迹
                    #   1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
                    #   2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
                    #   3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
                    ************************************************ */
			draw: function() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
			},

			handleCancel() {
				uni.navigateBack({
					delta: 1
				});
			},

			//清空画布
			handleReset: function() {
				that.ctx.clearRect(0, 0, that.width, that.height);
				that.ctx.draw(true);
				tempPoint = [];
			},

			//将签名笔迹上传到服务器，并将返回来的地址存到本地
			handleConfirm: function() {
				if (tempPoint.length == 0) {
					uni.showToast({
						title: '请先签名',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				uni.canvasToTempFilePath({
					canvasId: 'mycanvas',
					success: function(res) {
						let tempPath = res.tempFilePath;

						const ctx = uni.createCanvasContext('camCacnvs', that);
						ctx.translate(0, that.width);
						ctx.rotate((-90 * Math.PI) / 180);
						ctx.drawImage(tempPath, 0, 0, that.width, that.height);
						ctx.draw();
						that.rotates(tempPath)
						// that.uploadPic(tempPath)
					}
				});
			},
			//旋转图片，生成新canvas实例
			rotates(tempFilePaths) {
				const that = this
				var _this = this;
				uni.getImageInfo({
					// 获取图片的信息
					src: tempFilePaths,
					success: (res1) => {
						// 将canvas1的内容复制到canvas2中
						let canvasContext = uni.createCanvasContext('mycanvas', this)
						let rate = res1.height / res1.width
						let width = 300 / rate
						let height = 300
						_this.cavWidth = 300 / rate
						_this.cavWidth1 = 300
						canvasContext.translate(height / 2, width / 2)
						canvasContext.rotate((270 * Math.PI) / 180)
						canvasContext.drawImage(tempFilePaths, -width / 2, -height / 2, width, height)
						canvasContext.draw(false, (data) => {
							// 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
							uni.canvasToTempFilePath({
								// 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
								canvasId: 'mycanvas',
								fileType: 'png',
								quality: 1, //图片质量
								success(res2) {
									that.uploadPic(res2.tempFilePath)
									// 调用uni.uploadFile上传图片即可
									// console.log(res2)
									// _this.$emit('getImg',res2.tempFilePath);
								}
							}, _this)
						});
					}
				})
			},
			// 图片上传处理
			uploadPic(tempFile) {
				// 1、将本地图片上传到服务器（假装是七牛云服务器）
				// 2、将七牛云返回的链接，上传到我们的服务器平台
				uni.showLoading({
					title: '正在上传中...'
				})
				uni.uploadFile({
					url: config.uploadUrl + '/upload/uploadPic',
					filePath: tempFile,
					name: 'file',
					success: (uploadFileRes) => {

						uni.hideLoading()
						let path = JSON.parse(uploadFileRes.data)
						getMediaPath({
							id: path.urlId[0]
						}).then(res => {
							that.fileUrl = res.fileUrl.url
							this.$store.commit('SET_SIGN', res.fileUrl.url)
						})


						// let fileUrl = JSON.parse(uploadFileRes.data).data.url
						// //that.companyForm.cardBack = JSON.parse(uploadFileRes.data).data.url
						// let params={
						// 	type: '1',
						// 	role:'1',
						// 	signUrl: fileUrl,
						// 	modeId : this.modeId,
						// 	orderId:this.orderId,
						// 	signId:this.userId,
						// 	nameS: this.nameS,
						// 	cardId: this.cardId
						// }
						// saveSignature(params).then(res=>{
						// 	if(res.code === 200){
						// 		this.$modal.msgSuccess("签名上传成功");
						// 		// this.$tab.reLaunch("/pages/order/details");
						// 		uni.navigateTo({
						// 			url:'/packageA/pages/order/index?id='+this.orderId
						// 		})
						// 	}else{
						// 		this.$modal.msgError(res.msg);
						// 	}
						// 	uni.hideLoading();
						// })
					},
					fail: () => {
						uni.hideLoading();
						that.$modal.msgError("上传失败，请联系开发！");

					}
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: row;
	}

	.sign-box {
		width: 80%;
		height: 90%;
		margin: auto;
		display: flex;
		flex-direction: column;
		text-align: center;
	}

	.sign-view {
		height: 100%;
	}

	.sigh-btns {
		height: 100%;
		margin: auto;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
	}

	.btn {
		margin: auto;
		padding: 8rpx;
		transform: rotate(90deg);
		border: grey 1rpx solid;
	}

	.mycanvas {
		margin: auto 0rpx;
		background-color: #ececec;
	}

	.canvsborder {
		border: 1rpx solid #333;
		position: fixed;
		top: 0;
		left: 10000rpx;
	}
</style>